package com.neu.cloudfactory.controler;

import com.neu.cloudfactory.bean.Factory.Factory;
import com.neu.cloudfactory.bean.Login.LoginDTO;
import com.neu.cloudfactory.bean.Login.Result;
import com.neu.cloudfactory.bean.User.User;
import com.neu.cloudfactory.repository.FactoryRepository;
import com.neu.cloudfactory.repository.UserRepository;
import com.neu.cloudfactory.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Map;

@RestController
public class LoginControler {
    @Autowired
    private FactoryRepository factoryRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    LoginService loginService;

    @RequestMapping("/signup")
    public User addUser(@RequestBody Map<String, String> params){
        User user = new User();
        user.setName(params.get("name"));
        user.setAccount(params.get("account"));
        user.setPassword(params.get("password"));
        user.setTypeid(Integer.parseInt(params.get("typeid")));
        user.setConnection(params.get("connection"));
        try{
            user = userRepository.saveAndFlush(user);
            if(user.getTypeid()==1){
                Factory factory=new Factory(params.get("factoryname"),user.getId(),params.get("description"));
                factoryRepository.saveAndFlush(factory);
            }
        }catch(Exception e){
            return null;
        }
        return user;
    }

    @RequestMapping("/checkAccount/{account}")
    public int checkAccount(@RequestParam("account") String account){
        return userRepository.findByAccount(account).isPresent()?1:2;
    }

    @RequestMapping("/checkFactoryname/{factroyname}")
    public int checkFactoryname(@RequestParam("factroyname") String factroyname){
        return factoryRepository.findByName(factroyname).isPresent()?1:2;
    }

    @PostMapping(value = "/login")
    public Result login(@RequestBody LoginDTO loginDTO){
        return loginService.login(loginDTO);
    }

}
